package com.snifferx.dao;

import java.util.Collection;

import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.springframework.util.Assert;

import com.snifferx.commons.dao.GenericJpaDao;
import com.snifferx.domain.AuthorityEntity;
import com.snifferx.domain.UserEntity;

public class AuthorityJpaDao extends GenericJpaDao<AuthorityEntity, Long> implements AuthorityDao {

	public AuthorityJpaDao() {
		super(AuthorityEntity.class);
	}

	@Override
	public AuthorityEntity loadAuthorityByUserName(String userName) {
		Assert.notNull(userName);
		AuthorityEntity authority = null;
		Query query = getEntityManager()
				.createQuery("select a from " + getPersistentClass().getSimpleName() + " a where a.user.username = :userName").setParameter(
						"userName", userName);
		try {
			authority = (AuthorityEntity) query.getSingleResult();
		} catch (NoResultException e) {
			// do nothing
		}

		return authority;
	}

	@Override
	public Collection<Object> findAllJoin() {
		/*Query query = getEntityManager()
				.createNativeQuery(
						"SELECT U.USERNAME,U.FIRST_NAME,U.LAST_NAME,R.AUTHORITY,U.LOGIN_ATTEMPTS,U.ENABLED FROM USERS_LWC U LEFT JOIN AUTHORITIES_LWC R ON U.USERNAME = R.USERNAME");*/
		Query query = getEntityManager().createQuery("select u, r  FROM UserEntity u left outer join u.authorities r where  (r is null)   or (u.username = r.user.username)   ");
		//此处分页 weicheng test
		//query.setFirstResult(2);
		//query.setMaxResults(2);
		Collection<Object> values = null;
		try {
			values = query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return values;

	}
}
